package module

import (
	"dub/app/gate/tcp/cmdefine"
	"dub/common"
	"dub/define/grpcmodel"
	"dub/utils"
	"github.com/golang/protobuf/proto"
)

type UseModule struct {
	log    *utils.Logger
	useRpc *utils.RpcProxy
}

func (u *UseModule) OnMessage(id uint16, data []byte, ses common.ISession) bool {
	result := true
	switch id {
	case cmdefine.CmdSub_Use_Login:
		result = u.login(data, ses)
	}
	return result
}

func (u *UseModule) login(data []byte, sec common.ISession) bool {
	req := &grpcmodel.ModelSecRpcAgentReqFind{}
	err := proto.Unmarshal(data, req)
	if err != nil {
		u.log.Errorf("use_module.go login method proto.Unmarshal err. %v\n", err)
		return true
	}

	sec_agent := grpcmodel.NewISecRpcAgentClient(u.useRpc.Conn())
	reply, err := sec_agent.Login(u.useRpc.Context(), req)
	if err != nil {
		u.log.Errorf("use_module.go login method sec_agent.Login err. %v\n", err)
	}

	reData, err := proto.Marshal(reply)
	if err != nil {
		u.log.Errorf("use_module.go login method proto.Marshal err. %v\n", err)
		return true
	}

	sec.Send(cmdefine.CmdMain_Use, cmdefine.CmdSub_Use_Login, reData)

	return true
}

func NewUseModule(rpc *utils.RpcProxy) common.IMoudle {
	return &UseModule{
		log:    utils.NewLogger(),
		useRpc: rpc,
	}
}
